<template>
    <base-breadcrumb>
        <searchData ref="searchData" :search-data="searchArr" @search="search" />
        <a-card :bordered="false" style="over-flow: scroll">
            <div>
                <a-row>
                    <a-col :md="24" :sm="19">
                        <!-- 表格 -->
                        <list-table
                            ref="table"
                            :columns="columns"
                            :start-index="0"
                            row-key="planId"
                            @select-click="onSelectChange"
                            :request="loadData"
                            :export-permission="{ select: 'stm_004_exp_07', all: 'stm_004_expall_08' }"
                            :export-config="{
                                use: true,
                                select: $route.meta.title,
                                all: $route.meta.title
                            }"
                            :is-show-count-bar="false"
                        >
                            <a-button
                                slot="prefix"
                                v-btnPermission="'stm_004_add_01'"
                                class="mb12"
                                type="primary"
                                icon="plus"
                                @click="goAdd()"
                            >
                                科技计划新增
                            </a-button>
                            <a-collapse
                                slot="suffix"
                                v-model="activeKey"
                                :bordered="false"
                                expand-icon-position="right"
                                class="mb12"
                            >
                                <a-collapse-panel style="background: #e6f3fc; border: none" :show-arrow="false">
                                    <template slot="header">
                                        <a-row type="flex" justify="space-between" align="middle" style="width: 100%">
                                            <div>
                                                <a-icon style="color: #108ee9" type="exclamation-circle" />
                                                <span class="btn_right"
                                                    >已选择<a
                                                        ><b> {{ selectedRowKeys.length }} </b></a
                                                    >项</span
                                                >
                                                <span class="btn_right">总计：{{ allLoadData || 0 }}</span>
                                                <span v-if="simple.planTypeCount && simple.planTypeCount.length > 0"
                                                    ><span class="btn_right">小计:</span
                                                    ><span
                                                        v-for="(item, index) in simple.planTypeCount"
                                                        :key="index"
                                                        class="btn_right"
                                                    >
                                                        {{ `${item.name}:`
                                                        }}<a
                                                            ><b> {{ item.num }} </b></a
                                                        ></span
                                                    ></span
                                                >
                                            </div>
                                            <div>
                                                <a-button
                                                    :loading="loading"
                                                    class="btn_right"
                                                    type="primary"
                                                    @click.stop="getCollect(0)"
                                                >
                                                    汇总所有
                                                </a-button>
                                                <a-button
                                                    :loading="loading"
                                                    :disabled="!selectedRowKeys.length"
                                                    class="btn_right"
                                                    type="primary"
                                                    @click.stop="getCollect(1)"
                                                >
                                                    汇总选中
                                                </a-button>
                                                <a class="btn_right">
                                                    <span
                                                        >{{ activeKey.length > 0 ? '收起' : '展开' }}详细汇总信息</span
                                                    >
                                                    <a-icon :type="activeKey.length > 0 ? 'up' : 'down'" />
                                                </a>
                                            </div>
                                        </a-row>
                                    </template>
                                    <div>
                                        <div class="flex align-items-center">
                                            <span>年度：</span>
                                            <a-form-model-item class="requiredFormItem" style="margin-bottom: 0">
                                                <a-select v-model="year" style="width: 200px">
                                                    <a-select-option key="1" :value="-1">全部</a-select-option>
                                                    <a-select-option
                                                        :key="index"
                                                        :value="item.value"
                                                        v-for="(item, index) in searchArr.find(item => item.value === 'year').data"
                                                    >
                                                        {{ item.label }}
                                                    </a-select-option>
                                                </a-select>
                                            </a-form-model-item>
                                            <a-button
                                                type="primary"
                                                class="ml20p"
                                                @click="$refs.tableSummary.refresh(true)"
                                                >确定</a-button
                                            >
                                            <a-button
                                                type="primary"
                                                style="margin-left:10px"
                                                @click="exportCountPlanFn"
                                                v-btn-permission="'stm_004_exp_09'"
                                                >导出</a-button
                                            >
                                        </div>
                                        <a-tabs :active-key="args.countTableType" @change="switchSummary">
                                            <a-tab-pane
                                                key="1"
                                                tab="按总体情况"
                                                :disabled="countType == 1 && !selectedRowKeys.length"
                                            />
                                            <a-tab-pane
                                                key="2"
                                                tab="按分公司汇总"
                                                :disabled="countType == 1 && !selectedRowKeys.length"
                                            />
                                            <a-tab-pane
                                                key="3"
                                                tab="按项目汇总"
                                                :disabled="countType == 1 && !selectedRowKeys.length"
                                            />
                                        </a-tabs>
                                        <s-table
                                            ref="tableSummary"
                                            table-layout="fixed"
                                            size="default"
                                            row-key="id"
                                            :columns="columnsTotal"
                                            :data="loadDataSummary"
                                            :scroll="{ y: 300 }"
                                            :alert="true"
                                            show-size-changer
                                            show-quick-jumper
                                            :show-pagination="false"
                                            style="background: #fff"
                                        />
                                    </div>
                                </a-collapse-panel>
                            </a-collapse>
                            <!-- <s-table
              ref="table"
              row-key="planId"
              :scroll="{ x: 1300 }"
              :columns="columns"
              :data="loadData"
              show-size-changer
              show-quick-jumper
              :row-selection="rowSelection"
              show-pagination="auto"
            > -->
                            <div slot="actions" slot-scope="text, record">
                                <MoreButton>
                                <a  v-btn-permission="'stm_004_loo_02'" @click="handleSub(record)">查看</a>

                                <a
                                  v-btn-permission="'stm_004_editype_05'"
                                    v-if="record.planStatusCode == 0 || record.planStatusCode == 3"
                                    @click="handleEdit(record)"
                                    >编辑</a
                                >

                                <a
                                  v-btn-permission="'stm_004_del_06'"
                                    v-if="record.planStatusCode == 0 && record.export === 0"
                                    @click="handleRemove(record.planId)"
                                    >删除</a
                                >
                                <!-- 当状态为审批中 -->
                                <template v-if="record.planStatusCode != '0'">
                                    <a @click="$bus.$emit('showApprovalDetailsDialog', record.planId)"
                                        >审批详情</a
                                    >
                                </template>
                                </MoreButton>
                            </div>
                            <!-- 状态 -->
                            <template slot="planStatus" slot-scope="text, record">
                                <status-display :status-code="record.planStatusCode" is-approval />
                            </template>
                        </list-table>
                    </a-col>
                </a-row>
            </div>
        </a-card>
    </base-breadcrumb>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import {
    getPlansList,
    getPlansCollect,
    getExpertGroup,
    getExpertGroupExcept,
    removePlan,
    getMinDate,
    exportCountPlan
} from '@/api/science'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import OrgTreeSelect from '@/components/OrgTreeSelect'
import SelectAchievementType from '@/components/Select/SelectAchievementType' // 成果分类
import SelectAchievementLevel from '@/components/Select/SelectAchievementLevel' // 成果等级
// import { getOrgTree } TitleName '@/api/commons'
import ARow from 'ant-design-vue/es/grid/Row'
import Modal from '../plan/components/Modal'
import { Collapse } from 'ant-design-vue' // ant
import StatusDisplay from '@/components/StatusDisplay'
import BasePage from '@/views/basePage' // 编辑详情页基础配置

const columns = [
    // {
    //   title: '序号',
    //   scopedSlots: { customRender: 'serial' },
    // },
    {
        title: '项目名称',
        ellipsis: true,
        dataIndex: 'projectName',
        width: 160
    },
    {
        ellipsis: true,
        title: '所属分公司',
        dataIndex: 'branchCompany',
        width: 120
    },
    {
        title: '年度',
        dataIndex: 'year',
        width: 100
    },
    {
        title: '成果分类',
        dataIndex: 'achievementsType',
        width: 140
    },
    {
        title: '计划完成人',
        dataIndex: 'planEmployee',
        width: 140
    },
    {
        title: '成果名称',
        dataIndex: 'achievementsName',
        width: 120
    },
    {
        title: '计划成果等级',
        dataIndex: 'planLevelName',
        width: 160
    },
    {
        title: '完成成果等级',
        dataIndex: 'completeLevelName',
        width: 160
    },
    {
        title: '计划完成时间',
        dataIndex: 'planCompleteDate',
        width: 160
    },
    {
        title: '实际完成时间',
        dataIndex: 'completeDate',
        width: 160
    },
    {
        title: '完成状态',
        dataIndex: 'completeStatus',
        width: 140
    },
    {
        title: '状态',
        dataIndex: 'planStatus',
        scopedSlots: { customRender: 'planStatus' },
        width: 160
    },
    {
        title: '操作',
        dataIndex: 'actions',
        fixed: 'right',
        align: 'center',
        width: '180px',
        scopedSlots: { customRender: 'actions' }
    }
]
const renderContent = (value, row, index) => {
    const obj = {
        children: value,
        attrs: {}
    }
    if (index === 4) {
        obj.attrs.colSpan = 0
    }
    return obj
}

export default {
    name: 'a' + Date.now(),
    extends: new BasePage(),
    components: {
        ARow,
        STable,
        ACollapse: Collapse,
        ACollapsePanel: Collapse['Panel'],
        StatusDisplay
    },
    data() {
        this.columns = columns
        return {
            removeApi: { remove: removePlan }, // 删除api
            columnsTotal: [
                {
                    title: '成果分类',
                    dataIndex: 'typeName',
                    customRender: (text, row, index) => {
                        // this.$nextTick(() => {
                        let rowSpan = 1
                        if (
                            index != 0 &&
                            text === this.simple.planCountTable[index - 1]?.typeName &&
                            row.name === this.simple.planCountTable[index - 1]?.name
                        ) {
                            rowSpan = 0
                            // 若不是，则往下合并与改行考核内容一致行的总行数
                        } else {
                            rowSpan = [...this.simple.planCountTable].filter(
                                (i) => i.typeName == text && row.name === i.name
                            ).length
                        }
                        return {
                            children: text,
                            attrs: {
                                rowSpan: rowSpan
                            }
                        }
                        // })
                    }
                },
                {
                    title: '成果等级',
                    dataIndex: 'levelName'
                },
                {
                    title: '计划数量',
                    dataIndex: 'planNum'
                },
                {
                    title: '审核通过数量',
                    dataIndex: 'auditNum'
                },
                {
                    title: '工作完成率',
                    dataIndex: 'completeRate',
                    customRender: (e) => {
                        return (e * 100).toFixed(2) + '%'
                    }
                },
                {
                    title: '获得成果数量',
                    dataIndex: 'acquisitionNum'
                },
                {
                    title: '成果获得率',
                    dataIndex: 'acquisitionRate',
                    customRender: (e) => {
                        return (e * 100).toFixed(2) + '%'
                    }
                }
            ],
            activeKey: [],
            args: {
                countTableType: '1',
                ids: [] // 表格选中集合
            },
            loading: false,
            queryParam: {},
            allLoadData:null,
            init: false,
            countType: 0, // 汇总类型:0 所有;1 选中,
            year: -1,
            loadDataSummary: () => {
                if (!this.selectProjectId.length && this.countType == 1) {
                    return false
                }
                let params = { type: this.args.countTableType }
                if (this.countType == 1) {
                    params.ids = this.selectProjectId
                    // params.ids = this.selectProjectId.join()
                } else {
                    params = Object.assign({}, params, this.$refs.searchData.form.getFieldsValue())
                }
                if (this.year !== -1) {
                    params.year = this.year
                }
                this.loading = true
                return getPlansCollect(params)
                    .then((res) => {
                        this.loading = false
                        if (res.code === 200) {
                            this.simple = res.data
                            let datas = {
                                data: res.data.planCountTable
                            }
                            let e = this.args.countTableType
                            if (e == 1 && this.columnsTotal[0].dataIndex === 'name') {
                                this.columnsTotal.splice(0, 1)
                            } else if (e == 2 || e == 3) {
                                if (this.columnsTotal[0].dataIndex !== 'name') {
                                    this.$nextTick(() => {
                                        this.columnsTotal.unshift({
                                            title: ['分公司名称', '项目名称'][e - 2],
                                            dataIndex: 'name',
                                            customRender: (text, row, index) => {
                                                // this.$nextTick(() => {
                                                let rowSpan = 1
                                                if (index != 0 && text == this.simple.planCountTable[index - 1]?.name) {
                                                    rowSpan = 0
                                                    // 若不是，则往下合并与改行考核内容一致行的总行数
                                                } else {
                                                    rowSpan = [...this.simple.planCountTable].filter(
                                                        (i) => i.name == text
                                                    ).length
                                                }
                                                return {
                                                    children: text,
                                                    attrs: {
                                                        rowSpan: rowSpan
                                                    }
                                                }
                                            }
                                        })
                                    })
                                } else {
                                    this.columnsTotal[0].title = ['分公司名称', '项目名称'][e - 2]
                                }
                            }
                            return datas
                        }
                    })
                    .catch((res) => {
                        this.loading = false
                    })
            },
            // 加载数据方法 必须为 Promise 对象
            loadData: (parameter) => {
                const requestParameters = Object.assign({}, parameter, this.queryParam)
                return getPlansList(requestParameters).then((res) => {
                    if (res.code === 200) {
                        this.allLoadData = res.totalSize;
                        // this.$refs.table.clearSelected()
                        return res
                    }
                })
            },
            selectedRowKeys: [],
            selectedRows: [],
            selectorgId: [],
            selectconstructionDate: [],
            selectProjectId: [],
            simple: [],
            test: '',
            showTotal: false,
            advanced: false,
            searchArr: [
                // 搜索框
                // {
                //     name: '所属分公司',
                //     valueKey: 'branchCompanyId',
                //     placeholder: '请选择',
                //     type: SelectSubCompany
                // },
                {
                  name: '所属单位',
                  valueKey: 'searchQuery',
                  type: OrgTreeSelect,
                },
                // {
                //     name: '项目名称',
                //     placeholder: '请选择',
                //     valueKey: 'projectId',
                //     type: SelectProject
                // },
                {
                    name: '成果名称',
                    value: 'achievementsName',
                    type: 'input'
                },
                // {
                //   name: '所属分公司',
                //   value: 'orgName',
                //   type: 'input',
                // },
                // {
                //   name: '成果分类',
                //   value: 'achievementsType',
                //   type: 'input',
                // },
                {
                    name: '成果分类',
                    valueKey: 'achievementsType',
                    placeholder: '请选择',
                    type: SelectAchievementType
                },
                {
                    name: '成果等级',
                    placeholder: '请选择',
                    valueKey: 'achievementsLevel',
                    type: SelectAchievementLevel
                },
                {
                    name: '计划完成时间',
                    value: 'planCompleteDate',
                    type: 'date',
                    attr: { valueFormat: 'YYYY-MM-DD' }
                },
                // {
                //   name: '项目名称',
                //   value: 'projectName',
                //   type: 'input',
                // },
                // {
                //   name: '成果等级',
                //   value: 'completeLevelName',
                //   type: 'input',
                // },
                {
                    name: '实际完成时间',
                    value: 'completeDate',
                    type: 'date',
                    attr: { valueFormat: 'YYYY-MM-DD' }
                },
                {
                    name: '完成状态',
                    value: 'completeStatusCode',
                    type: 'select',
                    data: [
                        {
                            value: '待录入',
                            label: '待录入'
                        },
                        {
                            value: '申报中',
                            label: '申报中'
                        },
                        {
                            value: '申报通过',
                            label: '申报通过'
                        },
                        {
                            value: '申报驳回',
                            label: '申报驳回'
                        },
                        {
                            value: '获得',
                            label: '获得'
                        },
                        {
                            value: '未获得',
                            label: '未获得'
                        },
                        {
                            value: '完成审批中',
                            label: '完成审批中'
                        },
                        {
                            value: '驳回',
                            label: '驳回'
                        }
                    ]
                },
                {
                    name: '计划完成人',
                    value: 'completeEmployeeName',
                    type: 'input'
                },
                {
                    name: '年度',
                    value: 'year',
                    type: 'select',
                    data: []
                }
            ]
        }
    },
    computed: {
        rowSelection() {
            return {
                selectedRowKeys: this.selectedRowKeys,
                selectedRows: this.selectedRows, // 当前行所有数据
                onChange: this.onSelectChange
            }
        }
    },
    created() {
        this.getMinYear()
    },
    methods: {
        /**
         * 导出科技管理计划统计
         * @param parameter
         */
        async exportCountPlanFn(){
            let params = { type: this.args.countTableType,ids: this.selectProjectId }
            let expqueryParam = Object.assign({}, params, this.$refs.searchData.form.getFieldsValue())
            expqueryParam.year = this.year || null
            if (expqueryParam.year == '-1'){
                delete expqueryParam.year
            }
            if (expqueryParam.ids?.length<1){
                delete expqueryParam.ids
            }
            let res = await exportCountPlan(expqueryParam)
            this.handleDownload(res)
        },
    /**
     * 转义下载
     * @param parameter
     */
     handleDownload(res){
      console.log('res.data',res.data)
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      console.log('filenamefilename',filename)
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename.substring(filename.indexOf("''") + 2) // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
        async getMinYear() {
            let res = await getMinDate()
            if (res.code === this.SUCCESS_CODE) {
                let currentYear = moment().format('YYYY')
                if (res.data >= currentYear) {
                    this.searchArr.find(item => item.value === 'year').data.push({ label: currentYear, value: currentYear })
                } else {
                    for (let i = res.data; i <= currentYear; i++) {
                        this.searchArr.find(item => item.value === 'year').data.push({ label: i, value: i })
                    }
                }
            }
        },
        search(values) {
            this.queryParam = values
            this.$refs.table.refresh(true)
        },
        // 切换汇总信息
        switchSummary(e) {
            this.args.countTableType = e
            this.$refs.tableSummary.refresh(true)
        },
        goAdd() {
            this.$router.push({
                name: '/science/plots/addPlan',
                query: {
                    type: 'add'
                }
            })
        },
        handleTotal(value) {
            this.form.achievementsName = value.achievementsName
        },
        handleOrg(value) {
            // this.form.orgId = value.orgId
        },
        getCollect(e) {
            this.countType = e
            if (this.activeKey.length === 0) {
                this.activeKey = ['0']
                if (this.init) {
                    this.$nextTick(() => {
                        this.$refs.tableSummary.refresh(true)
                    })
                } else {
                    this.init = true
                }
            } else {
                this.$nextTick(() => {
                    this.$refs.tableSummary.refresh(true)
                })
            }
        },
        getGroup(value) {
            console.log(value)
            this.editForm = value
        },
        showEdit() {
            this.form = this.editForm
            console.log(this.form)
            this.groupAdd = true
        },
        showAdd() {
            this.groupAdd = true
        },
        handleAdd(record) {
            console.log(record)
        },
        getExpertGroup() {
            getExpertGroup().then((res) => {
                this.expertList = res.data
                console.log('专家组列表：' + res)
            })
        },
        deletes() {},
        handleDel() {
            this.$confirm({
                title: '提醒',
                content: '是否移除当前科技人员',
                okText: '确认',
                cancelText: '取消'
            })
        },
        onSearch(value) {
            console.log(value)
        },
        showModal() {
            this.visible = true
            // this.getOrgTree()
        },
        handleOk(e) {
            this.confirmLoading = true
            setTimeout(() => {
                this.visible = false
                this.confirmLoading = false
            }, 2000)
        },
        handleCancel(e) {
            this.visible = false
        },
        handleEdit(record) {
            this.$router.push({
                name: '/science/plots/addPlan',
                query: {
                    id: record.planId,
                    type: 'edit'
                }
            })
        },
        handleCancelGroup() {
            this.groupAdd = false
        },
        handleSub(value) {
            // console.log(JSON.stringify(value))
            this.$router.push({
                path: '/science/plan/details',
                query: {
                    id: value.planId
                }
            })
        },
        onSelectChange(e) {

            this.selectedRowKeys = e.keys
            this.selectedRows = e.rows
            this.selectorgId = []
            this.selectProjectId = []
            this.selectconstructionDate = []
            this.selectedRows.forEach((item) => {
                this.selectProjectId.push(item.planId)
            })
            // console.log(this.selectorgId)
        },
        toggleAdvanced() {
            this.advanced = !this.advanced
        },
        // getOrgTree(){
        //   getOrgTree().then((res)=>{
        //     this.companyList = res.data
        //   })
        // },
        onSelect(selectedKeys, info) {
            console.log(info.selectedNodes[0].data.props.id)
            let id = info.selectedNodes[0].data.props.id
            getExpertGroupExcept({ orgId: id, status: 1 }).then((res) => {
                console.log('不是专家组人员：' + res)
            })
        },
        resetSearchForm() {
            this.queryParam = {
                date: moment(new Date())
            }
        }
    }
}
</script>
<style scoped>
.sprite {
    background-color: #f2f2f2;
    height: 550px;
    width: 1px;
}

.item {
    background-color: #f2f2f2;
    height: 400px;
    width: 180px;
    padding: 10px;
}

.sideItem {
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #fff;
    text-align: center;
    cursor: pointer;
}

.sideItem:hover {
    background: #aaa;
}

.input {
    border-radius: 10px;
}

.font {
    font-weight: bold;
}

.expert {
    background-color: #eee;
    height: 300px;
    padding: 10px;
    text-align: center;
}

.selects {
    background-color: #e6f3fc;
    box-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    border-color: #d4f0fc;
    border-radius: 4px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    text-align: left;
    line-height: 24px;
    padding: 5px 10px;
    vertical-align: middle;
}
</style>
